package com.example.springsecuritystart.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    private String logoutUrl = null;

    public MyLogoutSuccessHandler() {}

    public MyLogoutSuccessHandler(String logoutUrl) {
        this.logoutUrl = logoutUrl;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> resp = new HashMap<>();
        resp.put("status", 200);
        resp.put("msg", this.getLogoutMsg());
        ObjectMapper om = new ObjectMapper();
        final String s = om.writeValueAsString(resp);
        response.getWriter().write(s);
    }

    public String getLogoutMsg() {
        if (this.logoutUrl == null) {
            return "注销成功";
        } else {
            return String.format("使用%s注销成功", this.logoutUrl);
        }
    }
}
